// ==UserScript==
// @name         小微权力平台数据自动填充工具
// @namespace    http://tampermonkey.net/
// @version      1.9
// @description  从后端获取真实数据填充到小微权力平台
// @author       e代农夫
// @match        http://59.231.9.97/*
// @grant        GM_addStyle
// @run-at       document-idle
// ==/UserScript==

(function () {
    'use strict';
    
    // ==== 防止脚本重复执行 ====
    if (window.scriptHasRun) {
        console.log('脚本已执行，防止重复运行');
        return;
    }
    window.scriptHasRun = true;
    
    // ==== 样式配置 ====
    GM_addStyle(`
  #fillDataBtn {
    position: absolute;
    top: 92px;
    right: 5.62vw;
    z-index: 999999;
    padding: 6px 12px;
    background: #588CEFFF !important;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
    height: 35px;
}
    #fillDataBtn:hover {
        background: #3F9DFDFF !important;
        opacity: 0.6;
    }
    #fillDataBtn:disabled {
        background: #3F9DFDFF !important;
        cursor: not-allowed;
        box-shadow: none;
    }
    `);
    
    // 穿透多层iframe定位目标元素
    function findElementInFrames(selector, maxDepth = 8) {
        // 带深度限制的递归查找
        const searchInFrames = (currentDoc, currentDepth = 0) => {
            if (currentDepth > maxDepth) {
                return null;
            }
            
            // 1. 检查当前文档
            let element = currentDoc.querySelector(selector);
            if (element) return element;
            
            // 2. 遍历当前文档中的iframe
            const iframes = currentDoc.querySelectorAll('iframe, frame');
            for (let i = 0; i < iframes.length; i++) {
                try {
                    const iframe = iframes[i];
                    const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                    
                    // 在iframe内直接查找
                    element = iframeDoc.querySelector(selector);
                    if (element) return element;
                    
                    // 仅对同源iframe递归查找
                    if (iframeDoc.location.host === window.location.host) {
                        const nestedElement = searchInFrames(iframeDoc, currentDepth + 1);
                        if (nestedElement) return nestedElement;
                    }
                } catch (e) {
                    console.log(`无法访问iframe[${i}]内容:`, e.message);
                    continue;
                }
            }
            return null;
        };
        
        // 从当前文档开始查找
        return searchInFrames(document);
    }
    
    // 查找包含特定文本的表格行
    function findRowByText(searchText) {
        const allRows = document.getElementsByTagName('tr');
        for (let i = 0; i < allRows.length; i++) {
            if (allRows[i].textContent.includes(searchText)) {
                return allRows[i];
            }
        }
        return null;
    }
    
    // 在表格行中根据索引查找单元格并填充数据
    function fillCellInRow(row, cellIndex, selector, value, eventType = 'input') {
        if (!row) return false;
        
        const tds = row.getElementsByTagName('td');
        if (tds.length > cellIndex) {
            const targetTd = tds[cellIndex];
            const targetElement = targetTd.querySelector(selector);
            if (targetElement) {
                targetElement.value = value || '';
                triggerEvents(targetElement, eventType);
                return true;
            }
        }
        return false;
    }
    
    // 触发元素事件
    function triggerEvents(element, eventType = 'input') {
        const events = ['input', 'change'];
        if (eventType === 'blur') events.push('blur');
        
        events.forEach(eventType => {
            element.dispatchEvent(new Event(eventType, {bubbles: true}));
        });
    }
    
    // 查找包含特定标签文本的输入框
    function findInputByLabelText(labelText, inputSelector = '.el-input__inner') {
        const labels = document.querySelectorAll('.el-form-item__content');
        for (let label of labels) {
            const fullText = label.textContent.trim();
            if (fullText.includes(labelText)) {
                const input = label.querySelector(inputSelector);
                if (input) return input;
            }
        }
        return null;
    }
    
    // 查找包含特定文本的复选框
    function findCheckboxByText(checkboxText) {
        const checkboxes = document.getElementsByClassName('el-checkbox');
        for (let i = 0; i < checkboxes.length; i++) {
            const label = checkboxes[i];
            const labelText = label.querySelector('.el-checkbox__label');
            if (labelText && labelText.textContent.trim() === checkboxText) {
                return label;
            }
        }
        return null;
    }
    
    // 处理Element UI下拉框辅助函数
    function fillElSelect(selectContainer, value) {
        if (!selectContainer || !value) return false;
        
        const selectElement = selectContainer.querySelector('.el-select');
        const inputElement = selectElement.querySelector('.el-input__inner');
        
        if (!selectElement || !inputElement) return false;
        
        // 使用Promise确保异步操作顺序
        return new Promise((resolve) => {
            // 先点击打开下拉框
            inputElement.click();
            
            // 延迟执行选项选择，等待下拉框完全展开
            setTimeout(() => {
                // 查找匹配的选项
                const dropdown = document.querySelector('.el-select-dropdown[style*="display: none;"]');
                // 如果下拉框隐藏了，再次点击打开
                if (dropdown) {
                    inputElement.click();
                }
                
                setTimeout(() => {
                    // 重新查找下拉框（可能是新出现的）
                    const allDropdowns = document.querySelectorAll('.el-select-dropdown');
                    let dropdown = null;
                    // 找到可见的下拉框
                    for (let i = 0; i < allDropdowns.length; i++) {
                        const style = window.getComputedStyle(allDropdowns[i]);
                        if (style.display !== 'none') {
                            dropdown = allDropdowns[i];
                            break;
                        }
                    }
                    
                    if (dropdown) {
                        const options = dropdown.querySelectorAll('.el-select-dropdown__item');
                        let targetOption = null;
                        
                        // 精确匹配选项文本
                        options.forEach(option => {
                            if (option.textContent.trim() === value.trim()) {
                                targetOption = option;
                            }
                        });
                        
                        // 如果找到了匹配的选项，则点击它
                        if (targetOption) {
                            targetOption.click();
                            resolve(true);
                        } else {
                            // 尝试模糊匹配
                            options.forEach(option => {
                                if (option.textContent.includes(value) || value.includes(option.textContent.trim())) {
                                    targetOption = option;
                                }
                            });
                            
                            if (targetOption) {
                                targetOption.click();
                                resolve(true);
                            } else {
                                // 关闭下拉框
                                inputElement.click();
                                resolve(false);
                            }
                        }
                    } else {
                        resolve(false);
                    }
                }, 200); // 给更多时间让下拉框渲染
            }, 100);
        });
    }


// 日期组件处理函数
// 日期组件处理函数
    function fillDateInput(dateContainer, dateValue) {
        if (!dateContainer || !dateValue) return false;
        
        const inputElement = dateContainer.querySelector('.el-input__inner');
        if (!inputElement) return false;
        
        // 设置值
        inputElement.value = dateValue;
        
        // 触发完整的事件序列
        const events = ['input', 'change', 'blur'];
        events.forEach(eventType => {
            const event = new Event(eventType, {
                bubbles: true,
                cancelable: true
            });
            inputElement.dispatchEvent(event);
        });
        
        // 针对Element UI日期组件的特殊处理
        setTimeout(() => {
            // 查找日期编辑器容器
            const datePicker = dateContainer.querySelector('.el-date-editor');
            if (datePicker) {
                // 触发日期选择事件
                const pickEvent = new CustomEvent('pick', {
                    detail: dateValue,
                    bubbles: true
                });
                datePicker.dispatchEvent(pickEvent);
                
                // 如果能访问到Vue实例，直接更新值
                if (datePicker.__vue__ && datePicker.__vue__.handleChange) {
                    try {
                        datePicker.__vue__.handleChange();
                    } catch (e) {
                        console.log('Vue实例方法调用失败:', e);
                    }
                }
            }
            
            // 确保input元素也触发blur事件
            inputElement.dispatchEvent(new Event('blur', {bubbles: true}));
        }, 100);
        
        return true;
    }
    
    
    // ==== 核心功能 ====
    // 创建填充按钮（仅在找到输入框后调用）
    function createFillButton() {
        // 移除当前iframe中可能存在的旧按钮
        const existingButton = document.getElementById('fillDataBtn');
        if (existingButton) existingButton.remove();
        
        // 创建按钮
        const stableContainer = document.querySelector('body > div.container, body > div.main, body');
        if (!stableContainer) {
            return;
        }
        
        const button = document.createElement('button');
        button.id = 'fillDataBtn';
        button.textContent = '自动填充村级工程项目（添加）表格';
        stableContainer.appendChild(button);
        
        // 点击事件绑定
        button.addEventListener('click', async () => {
            button.disabled = true;
            try {
                await fillProjectData();
            } catch (error) {
                console.error('填充失败:', error);
                alert(`⚠️ 数据填充失败！\n\n错误详情：${error.message}`);
            } finally {
                button.disabled = false;
            }
        });
    }
    
    // 检查必要的表单字段是否存在
    function checkRequiredFields() {
        try {
            // 查找项目名称输入框
            const projectInfoRow = findRowByText('项目名称 *');
            let hasProjectNameInput = false;
            let hasProjectAddressInput = false;
            let hasConstructionContentInput = false;
            
            if (projectInfoRow) {
                const infoTds = projectInfoRow.getElementsByTagName('td');
                
                // 检查项目名称输入框是否存在
                if (infoTds.length > 1) {
                    const nameTd = infoTds[1];
                    hasProjectNameInput = !!nameTd.querySelector('input[type="text"], .el-input__inner');
                }
                
                // 检查项目地址输入框是否存在
                if (infoTds.length > 3) {
                    const addressTd = infoTds[3];
                    hasProjectAddressInput = !!addressTd.querySelector('input[type="text"], .el-input__inner');
                }
            }
            
            // 检查主要建设内容输入框是否存在
            const contentRow = findRowByText('主要建设内容 *');
            if (contentRow) {
                const contentTds = contentRow.getElementsByTagName('td');
                if (contentTds.length > 1) {
                    const contentTd = contentTds[1];
                    hasConstructionContentInput = !!contentTd.querySelector('.el-textarea .el-textarea__inner');
                }
            }
            
            // 返回条件：所有字段都存在
            return hasProjectNameInput && hasProjectAddressInput && hasConstructionContentInput;
        } catch (error) {
            console.error('检查必要字段时出错:', error);
            return false;
        }
    }
    
    // 提取设备指纹生成逻辑到独立函数
    const initializeDeviceFingerprint = async () => {
        // 收集更丰富的设备特征
        const features = {
            userAgent: navigator.userAgent,
            screenResolution: `${window.screen.width}x${window.screen.height}`,
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            hardwareConcurrency: navigator.hardwareConcurrency || 'unknown',
            language: navigator.language,
            platform: navigator.platform,
            vendor: navigator.vendor,
            doNotTrack: navigator.doNotTrack,
            cookieEnabled: navigator.cookieEnabled,
            plugins: navigator.plugins.length,
            mimeTypes: navigator.mimeTypes.length,
            canvas: await getCanvasFingerprint(),
            WebGL: await getWebGLFingerprint(),
            audio: await getAudioFingerprint(),
            localStorage: localStorage.getItem('fingerprint') || '',
            sessionStorage: sessionStorage.getItem('fingerprint') || '',
        };
        
        // 序列化特征数据
        const dataString = JSON.stringify(features);
        
        // 使用哈希算法
        const cyrb53 = function (str, seed = 0) {
            let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
            for (let i = 0, ch; i < str.length; i++) {
                ch = str.charCodeAt(i);
                h1 = Math.imul(h1 ^ ch, 2654435761);
                h2 = Math.imul(h2 ^ ch, 1597334677);
            }
            h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
            h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
            return (h2 >>> 0).toString(16).padStart(8, '0') + (h1 >>> 0).toString(16).padStart(8, '0');
        };
        
        return cyrb53(dataString);
    };
    
    // 获取 Canvas 指纹
    async function getCanvasFingerprint() {
        try {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            ctx.font = '14px sans-serif';
            ctx.textAlign = 'center';
            ctx.fillText('Hello World', 100, 100);
            return canvas.toDataURL();
        } catch (e) {
            return 'canvas-error';
        }
    }
    
    // 获取 WebGL 指纹
    async function getWebGLFingerprint() {
        try {
            const canvas = document.createElement('canvas');
            const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
            if (!gl) return 'webgl-not-supported';
            
            const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
            const vendor = debugInfo ? gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL) : 'unknown';
            const renderer = debugInfo ? gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) : 'unknown';
            
            return `${vendor}-${renderer}`;
        } catch (e) {
            return 'webgl-error';
        }
    }
    
    // 获取 Audio 指纹
    async function getAudioFingerprint() {
        try {
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            const buffer = audioContext.createBuffer(1, 1, 44100);
            const source = audioContext.createBufferSource();
            source.buffer = buffer;
            source.connect(audioContext.destination);
            source.start();
            
            const data = await new Promise((resolve) => {
                const dataArray = new Float32Array(buffer.length);
                const analyzer = audioContext.createAnalyser();
                analyzer.fftSize = 256;
                analyzer.connect(audioContext.destination);
                analyzer.getByteFrequencyData(dataArray);
                resolve(dataArray.join(','));
            });
            
            return data;
        } catch (e) {
            return 'audio-error';
        }
    }
    
    // 从后端获取数据
    async function fetchData() {
        try {
            const fingerprint = await initializeDeviceFingerprint();
            
            // 验证指纹不为空
            if (!fingerprint || fingerprint.trim() === '') {
                throw new Error('设备指纹生成失败');
            }
            
            // 构建请求URL
            const params = new URLSearchParams();
            params.append('fingerprint', fingerprint);
            const url = `https://api.zszis.cn/searchapi/searchdata/list?${params.toString()}`;
            
            const response = await fetch(url, {
                method: 'GET',
                mode: 'cors',
                headers: {
                    'Content-Type': 'application/json',
                    'Referer': 'http://59.231.9.97/',
                    'sec-fetch-mode': 'cors',
                    'sec-fetch-site': 'cross-site'
                }
            });
            
            if (!response.ok) {
                throw new Error(`HTTP错误! 状态: ${response.status}`);
            }
            
            const result = await response.json();
            
            if (result.success) {
                if (result.data && result.data.length > 0) {
                    // 查找匹配设备指纹的数据
                    const matchingData = result.data.find(item => item.fingerprint === fingerprint);
                    if (matchingData) {
                        return matchingData;
                    } else {
                        throw new Error('未找到匹配的设备数据');
                    }
                } else {
                    throw new Error('后端未返回有效数据');
                }
            } else {
                throw new Error(result.message || '获取数据失败');
            }
        } catch (error) {
            console.error('获取数据失败:', error);
            throw new Error('无法获取数据，请确保已在数据检索页面中提交了数据');
        }
    }
    
    // 数据填充核心逻辑
    async function fillProjectData() {
        try {
            const projectData = await fetchData();
            
            // 移除必填字段检查，改为逐个字段检查
            
            // ✅ 新增：检查 editTime 是否超过 10 分钟
            const now = new Date().getTime();
            const editTime = new Date(projectData.editTime).getTime();
            const timeDiff = now - editTime;
            
            const tenMinutes = 10 * 60 * 1000; // 10分钟
            
            if (timeDiff > tenMinutes) {
                alert('⚠️ 无有效数据！\n\n数据已超过10分钟，可能已失效，请重新提交数据。');
                return;
            }
            
            // 填充项目名称与项目地址（参照日期字段格式）
            const projectInfoRow = findRowByText('项目名称 *');
            if (projectInfoRow) {
                // 填充项目名称（第2个<td>，索引1）- 仅在有数据时填充
                if (projectData.projectName) {
                    fillCellInRow(projectInfoRow, 1, '.el-input .el-input__inner', projectData.projectName);
                }
                
                // 填充项目地址（第4个<td>，索引3）- 仅在有数据时填充
                if (projectData.constructionAddress) {
                    fillCellInRow(projectInfoRow, 3, '.el-input .el-input__inner', projectData.constructionAddress);
                }
            }
            
            // 填充主要建设内容字段（一行两格，参照竣工验收意见）
            const contentRow = findRowByText('主要建设内容 *');
            if (contentRow) {
                if (projectData.constructionContent) {
                    const contentTds = contentRow.getElementsByTagName('td');
                    if (contentTds.length > 1) {
                        const contentTd = contentTds[1];
                        const contentTextarea = contentTd.querySelector('.el-textarea .el-textarea__inner');
                        if (contentTextarea) {
                            contentTextarea.value = projectData.constructionContent || "";
                            contentTextarea.dispatchEvent(new Event('input', {bubbles: true}));
                            contentTextarea.dispatchEvent(new Event('change', {bubbles: true}));
                        }
                    }
                }
            }
            
            // 填充财政/投资总额字段
            if (projectData.totalPrice) {
                const fiscalInput = findInputByLabelText('财政', '.el-input__inner');
                if (fiscalInput) {
                    fiscalInput.value = projectData.totalPrice || '';
                    triggerEvents(fiscalInput, 'blur');
                }
            }
            
            // 填充自筹字段（固定值）
            const selfRaisedInput = findInputByLabelText('自筹', '.el-input__inner');
            if (selfRaisedInput) {
                selfRaisedInput.value = '0.00';
                triggerEvents(selfRaisedInput, 'blur');
            }
            
            // 填充其他来源字段（固定值）
            const otherSourceInput = findInputByLabelText('其他来源', '.el-input__inner');
            if (otherSourceInput) {
                otherSourceInput.value = '0.00';
                triggerEvents(otherSourceInput, 'blur');
            }
            
            // 填充建设周期字段
            if (projectData.constructionPeriod) {
                const constructionPeriodContainer = document.querySelector(
                    '.el-date-editor.el-range-editor.el-date-editor--daterange'
                );
                
                if (constructionPeriodContainer) {
                    const startDateInput = constructionPeriodContainer.querySelector('input[placeholder="开始日期"]');
                    const endDateInput = constructionPeriodContainer.querySelector('input[placeholder="结束日期"]');
                    
                    if (startDateInput && endDateInput) {
                        const periodStr = projectData.constructionPeriod.trim();
                        const startDateStr = periodStr.substring(0, 10).trim();
                        const endDateStr = periodStr.substring(periodStr.length - 10).trim();
                        startDateInput.value = startDateStr;
                        endDateInput.value = endDateStr;
                        
                        // 触发事件
                        startDateInput.dispatchEvent(new Event('input', {bubbles: true}));
                        endDateInput.dispatchEvent(new Event('input', {bubbles: true}));
                        constructionPeriodContainer.dispatchEvent(new Event('change', {bubbles: true}));
                    }
                }
            }
            
            // 默认选中"村民议事会会议"复选框
            const targetCheckbox = findCheckboxByText('村民议事会会议');
            if (targetCheckbox) {
                const checkboxInput = targetCheckbox.querySelector('.el-checkbox__original');
                const checkboxInner = targetCheckbox.querySelector('.el-checkbox__input');
                
                if (checkboxInput) {
                    checkboxInput.checked = true;
                    checkboxInner.setAttribute('aria-checked', 'true');
                    checkboxInput.dispatchEvent(new Event('change', {bubbles: true}));
                }
            }
            
            // 填充招标方式与招标单位（一行四列标准结构）
            const biddingRow = findRowByText('招标方式');
            if (biddingRow) {
                // 招标方式（下拉选择器）- 第2列<td>（索引1）
                const biddingFormTd = biddingRow.getElementsByTagName('td')[1];
                if (biddingFormTd && projectData.biddingForm) {
                    await fillElSelect(biddingFormTd, projectData.biddingForm);
                }
                
                // 招标单位（文本输入框）- 第4列<td>（索引3）
                if (projectData.biddingUnit) {
                    fillCellInRow(biddingRow, 3, '.el-input .el-input__inner', projectData.biddingUnit, 'blur');
                }
            }
            
            // 填充项目中标单位（个人）字段
            const bidRow = findRowByText('项目中标单位（个人）');
            if (bidRow) {
                // 中标单位输入框位于第2个<td>（索引1）
                if (projectData.winningBidder) {
                    fillCellInRow(bidRow, 1, '.el-input .el-input__inner', projectData.winningBidder);
                }
                
                // 中标价格输入框位于第4个<td>（索引3）
                if (projectData.bidAmount) {
                    fillCellInRow(bidRow, 3, '.el-form-item__content .el-input .el-input__inner', projectData.bidAmount || "0.00");
                }
            }
            
            // 填充项目承建单位（个人）字段
            const constructRow = findRowByText('项目承建单位（个人）');
            if (constructRow) {
                // 承建单位输入框位于第2个<td>（索引1）
                if (projectData.constructionUnit) {
                    fillCellInRow(constructRow, 1, '.el-input .el-input__inner', projectData.constructionUnit);
                }
                
                // 承建单位负责人输入框位于第4个<td>（索引3）
                if (projectData.constructionUnitLeader) {
                    const leaderTd = constructRow.getElementsByTagName('td')[3];
                    if (leaderTd) {
                        const leaderInput = leaderTd.querySelector('.el-input__inner') ||
                            leaderTd.querySelector('.el-form-item__content .el-input .el-input__inner');
                        
                        if (leaderInput) {
                            leaderInput.value = projectData.constructionUnitLeader || "";
                            triggerEvents(leaderInput);
                        }
                    }
                }
            }
            
            // 填充项目启动日期与竣工验收日期
            const dateRow = findRowByText('项目启动日期');
            if (dateRow) {
                // 项目启动日期（第2个<td>，索引1）
                if (projectData.projectStartDate) {
                    fillDateInput(dateRow.getElementsByTagName('td')[1], projectData.projectStartDate);
                    await new Promise(resolve => setTimeout(resolve, 300));
                }
                
                // 竣工验收日期（第4个<td>，索引3）
                if (projectData.completionDate) {
                    fillDateInput(dateRow.getElementsByTagName('td')[3], projectData.completionDate);
                    await new Promise(resolve => setTimeout(resolve, 300));
                }
                
                // 添加额外延迟确保日期组件完全处理
                await new Promise(resolve => setTimeout(resolve, 500));
            }
            
            // 填充项目监督人员与竣工验收人员
            const supervisorRow = findRowByText('项目监督人员');
            if (supervisorRow) {
                // 项目监督人员（第2个<td>，索引1）
                if (projectData.constructionSupervisor) {
                    fillCellInRow(supervisorRow, 1, '.el-input .el-input__inner', projectData.constructionSupervisor);
                }
                
                // 竣工验收人员（第4个<td>，索引3）
                if (projectData.constructionEndPerson) {
                    fillCellInRow(supervisorRow, 3, '.el-input .el-input__inner', projectData.constructionEndPerson);
                }
            }
            
            // 填充竣工验收意见字段
            const opinionRow = findRowByText('竣工验收意见');
            if (opinionRow) {
                if (projectData.constructionEndOpinion) {
                    const opinionTds = opinionRow.getElementsByTagName('td');
                    if (opinionTds.length > 1) {
                        const opinionTd = opinionTds[1];
                        const opinionTextarea = opinionTd.querySelector('.el-textarea .el-textarea__inner');
                        if (opinionTextarea) {
                            opinionTextarea.value = projectData.constructionEndOpinion || "";
                            opinionTextarea.dispatchEvent(new Event("input", {bubbles: true}));
                            opinionTextarea.dispatchEvent(new Event("change", {bubbles: true}));
                        }
                    }
                }
            }
        } catch (error) {
            console.error('数据填充失败:', error);
            alert(`⚠️ 数据处理失败！\n\n错误详情：${error.message}`);
        }
    }
    
    
    // ==== 初始化 ====
    function initScript() {
        if (window.initHasRun) return;
        window.initHasRun = true;
        
        // 更新选择器以匹配任意目标输入框
        const targetSelector = 'td[colspan="2"] .el-input__inner, td[colspan="5"] .el-textarea__inner';
        let buttonCreated = false;
        
        // 检查并创建按钮（仅当找到目标输入框且必要字段不为空时）
        const checkAndCreateButton = () => {
            if (buttonCreated) return; // 防止重复创建
            
            // 关键：先查找目标输入框
            const targetInput = findElementInFrames(targetSelector);
            if (targetInput && checkRequiredFields()) {
                createFillButton();
                buttonCreated = true;
                return true; // 表示已创建
            }
            return false; // 表示未找到或条件不满足
        };
        
        // 1. DOM变化监听：当页面结构更新时检查输入框和字段
        const observer = new MutationObserver((mutations) => {
            mutations.forEach((mutation) => {
                mutation.addedNodes.forEach((node) => {
                    if (node.nodeType === 1) { // Element node
                        const inputs = node.querySelectorAll('.el-input__inner');
                        inputs.forEach(input => {
                            if (input.placeholder.includes('项目监督人员') ||
                                input.placeholder.includes('竣工验收人员')) {
                                input.setAttribute('autocomplete', 'on');
                            }
                        });
                    }
                });
            });
        });
        
        observer.observe(document.body, {childList: true, subtree: true});
        
        // 2. 定时重试机制：定期检查输入框（最多10次，每1秒一次）
        let retryCount = 0;
        const maxRetries = 10;
        const retryInterval = setInterval(() => {
            retryCount++;
            if (checkAndCreateButton() || retryCount >= maxRetries) {
                clearInterval(retryInterval);
                observer.disconnect();
            }
        }, 1000);

        // 开始观察整个文档
        observer.observe(document, {
            childList: true,
            subtree: true
        });

        // 同时检查已存在的输入框
        document.querySelectorAll('.el-input__inner').forEach(input => {
            if (input.placeholder.includes('项目监督人员') ||
                input.placeholder.includes('竣工验收人员')) {
                input.setAttribute('autocomplete', 'on');
            }
        });
        
        (function modifyInputs() {
            // 修改现有输入框
            document.querySelectorAll('.el-input__inner').forEach(input => {
                if (input.placeholder.includes('项目监督人员') ||
                    input.placeholder.includes('竣工验收人员')) {
                    input.setAttribute('autocomplete', 'on');
                }
            });
            
            // 监听DOM变化以处理动态添加的输入框
            const observer = new MutationObserver(mutations => {
                mutations.forEach(mutation => {
                    mutation.addedNodes.forEach(node => {
                        if (node.nodeType === 1) { // Element node
                            const inputs = node.querySelectorAll('.el-input__inner');
                            inputs.forEach(input => {
                                if (input.placeholder.includes('项目监督人员') ||
                                    input.placeholder.includes('竣工验收人员')) {
                                    input.setAttribute('autocomplete', 'on');
                                }
                            });
                        }
                    });
                });
            });
            
            observer.observe(document, {
                childList: true,
                subtree: true
            });
        })();
    }
    
    // 启动初始化
    initScript();
})();
